package com.boomsecret.juc.tools;

import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;

/**
 * @author wangjinliang on 2019/1/23.
 */
public class PhaserCountDownLatchDemo {
    private static final int THREAD_COUNT = 5;

    public static void main(String[] args) {
        Phaser phaser = new Phaser(1);

        Thread[] threads = new Thread[THREAD_COUNT];
        for (int index = 0; index < THREAD_COUNT; index ++) {
            threads[index] = new Thread(new PhaserCyclicBarrierDemo.CustomRunnable(phaser));
            threads[index].start();
        }

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        phaser.arrive();
        System.out.println("main end.");
    }

    public static class CustomRunnable implements Runnable {
        private Phaser phaser;

        public CustomRunnable(Phaser phaser) {
            this.phaser = phaser;
        }

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + " start");
            this.phaser.awaitAdvance(this.phaser.getPhase());
            System.out.println(Thread.currentThread().getName() + " end");
        }
    }
}
